<!--用户管理-->
<template>
  <!-- 搜索卡片 -->
  <el-card shadow="hover" style="margin:20px;height: 70px;">
    <el-form :inline="true">
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="用户名" style="width: 90%;">
            <el-input placeholder="请输入用户名" v-model="search.username"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="用户电话" style="width: 90%;">
            <el-input placeholder="请输入电话" v-model="search.phone"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item style="margin-left: 30px;">
            <el-button @click="resetSearch">重置</el-button>
            <el-button type="primary" @click="searchUser">查询</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-card>

  <el-card style="margin: 20px;height: 73vh">
    <div style="margin:10px 0 40px 10px;">
      用户列表
      <div style="float: right">
        <el-button type="success" @click="addUser">添加用户</el-button>
        <el-button type="primary" @click="selectAll">全选</el-button>
        <el-button type="primary" @click="clearSelection">取消全选</el-button>
        <el-button type="danger"  @click="batchDelete">批量删除</el-button>
        <el-button type="primary" @click="exportUser">导出用户</el-button>
      </div>
    </div>

    <el-table ref="multipleTableRef"
              @selection-change="handleSelectionChange"
              :data="paginatedData" stripe
              style="margin-top: 20px; height: 450px">
      <template>
        <el-empty description="NO DATA"/>
      </template>
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column type="index" label="编号" width="80" align="center"/>
      <el-table-column label="用户名" prop="username" align="center"/>
      <el-table-column label="用户昵称" prop="nickname" align="center"/>
      <el-table-column label="手机号" prop="phone" width="110" align="center"/>
      <el-table-column label="用户邮箱" prop="email" align="center"/>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button link type="primary" @click="deleteUser(scope.row.id)">删除</el-button>
          <el-button link type="primary" @click="viewUser(scope.row.id)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next, jumper"
        :total="tableData.length"
        @current-change="handlePageChange"
        style="margin-top:20px;margin-left:  35%"
    />
  </el-card>

  <el-dialog :title="userTitle"
             v-model="userVisible"
             style=" position: absolute;
                       top: 30%;
                       left: 40%;
                       transform: translate(-30%, -40%);
                       width: 600px;
                       padding: 40px;"
             :before-close="handleClose"
  >
    <el-form ref="form" label-width="80px" label-position="top">
      <el-form-item label="手机号">
        <el-input type="text" placeholder="请输入手机号" v-model="saveUserFrom.phone"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="danger" @click="handleClose">取消</el-button>
      <el-button type="primary" @click="saveUser">保存</el-button>
    </template>
  </el-dialog>

  <el-dialog v-model="particularsVisible" style="width: 900px;
                                                 position: absolute;
                                                 top: 30%;left: 35%;
                                                 transform: translate(-20%, -30%);
                                                 padding: 20px">
    <el-descriptions title="详情信息"
                     border
                     label-width="80px">
      <el-descriptions-item
          :rowspan="2"
          :width="140"
          label="图片"
          align="center"
      >
        <el-image
            v-if="particularsData && particularsData.avatar"
            style="width: 100px; height: 100px"
            :src="BASE_URL + particularsData.avatar"
            alt="User Avatar"
        />
      </el-descriptions-item>
      <el-descriptions-item label="用户名" align="center">{{ particularsData.username }}</el-descriptions-item>
      <el-descriptions-item label="用户昵称" align="center">{{ particularsData.nickname }}</el-descriptions-item>
      <el-descriptions-item label="用户电话" align="center">{{ particularsData.phone }}</el-descriptions-item>
      <el-descriptions-item label="用户邮箱" align="center">{{ particularsData.email }}</el-descriptions-item>
      <el-descriptions-item label="性别" align="center">
        <template #default="scope">
          <span v-if="particularsData.gender  == 1">男</span>
          <span v-else-if="particularsData.gender  == 2">女</span>
        </template>
      </el-descriptions-item>
      <el-descriptions-item label="生日" align="center">{{ particularsData.birthday }}</el-descriptions-item>
      <el-descriptions-item label="创建时间" align="center">{{ particularsData.createTime }}</el-descriptions-item>
      <el-descriptions-item label="个性签名" align="left">{{ particularsData.info }}</el-descriptions-item>



    </el-descriptions>

  </el-dialog>
</template>

<script setup>
import {computed, onMounted, ref} from 'vue';
import axios from "axios";
import {ElMessage, ElMessageBox} from "element-plus";
import qs from "qs";
import selectedRows from "core-js/internals/array-iteration";
import * as XLSX from "xlsx";

const tableData = ref([]);
const currentPage = ref(1);// 默认显示页码
const pageSize = ref(10); // 每页显示6条

// 计算当前页面的数据
const paginatedData = computed(() => {
  const offset = (currentPage.value - 1) * pageSize.value;
  return tableData.value.slice(offset, offset + pageSize.value);
});

// 分页变化时触发
const handlePageChange = (newPage) => {
  currentPage.value = newPage;
};
const search = ref({
  username: '',
  phone: '',
  vip: ''
});
const searchUser = () => {
  let data = qs.stringify(search.value);
  axios.get(BASE_URL + '/v1/user/select?' + data)
      .then((response) => {
        if (response.data.code === 2000) {
          tableData.value = response.data.data;
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          });
        }
      })
}
onMounted(() => {
  searchUser();
})
const resetSearch = () => {
  search.value = {
    nickname: '',
    phone: '',
    vip: ''
  };
  searchUser();
};
const userVisible = ref(false);
const userTitle = ref('添加用户');
const handleClose = () => {
  ElMessageBox.confirm('您确定要取消吗', '提示', {
    customClass: 'custom-message-box',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  }).then(() => {
    Info('已取消保存');
    saveUserFrom.value = {username: ''};
    userVisible.value = false;
  }).catch(() => {

  });
};
const addUser = () => {
  userVisible.value = true;
  userTitle.value = '添加用户';
};
const times = ref([]);
const saveUserFrom = ref({
      phone: '',
    }
)
const saveUser = () => {
  if (saveUserFrom.value.phone === '' || saveUserFrom.value.phone === null) {
    errorInfo('请输入手机号');
    return;
  }
  if (saveUserFrom.value.phone.length !== 11) {
    errorInfo('请输入正确的手机号');
    return;
  }

  let data = qs.stringify(saveUserFrom.value);
  axios.post(BASE_URL + '/v1/user/save', data)
      .then((response) => {
        if (response.data.code === 2000) {
          OKInfo('保存成功!')
          userVisible.value = false;
          saveUserFrom.value = {};
          times.value = [];
          searchUser();
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          })
        }
      })
}

const deleteUser = (id) => {
  ElMessageBox.confirm('您确定要删除吗', '提示', {
    customClass: 'custom-message-box',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  }).then(() => {
    return ElMessageBox.prompt('请输入您的工号以确认删除操作:', '工号验证', {
      customClass: 'custom-message-box',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      draggable: true,
    });
  }).then(({ value }) => {
    // 手动验证输入的工号格式（假设工号是数字）
    const inputPattern = /^\d+$/;
    if (!inputPattern.test(value)) {
      errorInfo('工号格式不正确')
      return Promise.reject(); // 拒绝继续执行
    }
    const getEmployeeJobNumber = getEmployee().jobNumber;
    // 验证输入的工号是否匹配当前用户的工号
    if (value !== getEmployeeJobNumber) {
      console.log('value:'+ value)
      console.log('getEmployeeJobNumber:'+ getEmployeeJobNumber)
      errorInfo('工号验证失败，请重新输入正确的工号。')
      return Promise.reject(); // 拒绝继续执行
    }

    return  axios.delete(BASE_URL + '/v1/user/delete/' + id);
  }).then(() => {
    axios.delete(BASE_URL + '/v1/user/delete/' + id)
        .then((response) => {
          if (response.data.code === 2000) {
            OKInfo('删除成功!')
            searchUser();
          } else {
            ElMessage({
              message: response.data.msg,
              type: 'error',
              showClose: true,
              center: true,
            })
          }
        })
  }).catch(() => {
    Info('已取消删除')
  });
}

const particularsData = ref({});
const particularsVisible = ref(false);
const viewUser = (id) => {
  particularsVisible.value = true;
  axios.get(BASE_URL + '/v1/user/select?id=' + id)
      .then((response) => {
        if (response.data.code === 2000) {
          particularsData.value = response.data.data[0];
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          })
        }
      })
}

// 表格引用
const multipleTableRef = ref(null);
// 行ID
const selectedIdsValue = ref([]);
// 监听选择变化
const handleSelectionChange = (selection) => {
  // 更新当前选中的行
  selectedRows.value = selection;
  // 提取所有选中行的ID
  selectedIdsValue.value = selection.map(row => row.id);
};
// 全选方法
const selectAll = () => {
  multipleTableRef.value.toggleAllSelection();
};

// 取消全选的方法
const clearSelection = () => {
  multipleTableRef.value.clearSelection();
};

// 批量删除的方法
const batchDelete = () => {
  if (selectedIdsValue.value.length===0) {
    Info('请选择要删除的行');
    return;
  }
  let data = selectedIdsValue.value.join(',');
  ElMessageBox.confirm('确定删除选中的员工吗？', '提示', {
    customClass: 'custom-message-box',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  }).then(() => {
    return ElMessageBox.prompt('请输入您的工号以确认删除操作:', '工号验证', {
      customClass: 'custom-message-box',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      draggable: true,
    });
  }).then(({ value }) => {
    // 手动验证输入的工号格式（假设工号是数字）
    const inputPattern = /^\d+$/;
    if (!inputPattern.test(value)) {
      errorInfo('工号格式不正确')
      return Promise.reject(); // 拒绝继续执行
    }
    const getEmployeeJobNumber = getEmployee().jobNumber;
    // 验证输入的工号是否匹配当前用户的工号
    if (value !== getEmployeeJobNumber) {
      console.log('value:'+ value)
      console.log('getEmployeeJobNumber:'+ getEmployeeJobNumber)
      errorInfo('工号验证失败，请重新输入正确的工号。')
      return Promise.reject(); // 拒绝继续执行
    }

    return   axios.delete(BASE_URL + '/v1/user/delete/batch/' + data);
  }).then(() => {
    axios.delete(BASE_URL + '/v1/user/delete/batch/' + data)
        .then((response) => {
          if(response.data.code === 2000) {
            OKInfo('删除成功!')
            searchUser();
          } else {
            ElMessage({
              message: response.data.msg,
              type: 'error',
              showClose: true,
              center: true,
            })
          }
        })
  }).catch(()=>{
    Info('已取消删除')
  });

};

const exportUser = () => {
  searchUser();
  try {
    // 定义固定的表头
    const headers = [
      'id', 'username', 'nickname', 'password', 'birthday', 'gender',  'phone', 'email', 'avatar',
      'vip', 'startTime', 'endTime', 'info', 'createTime', 'updateTime'

    ];

    // 将 JSON 数据转换为二维数组
    const data = tableData.value.map(user => headers.map(header => user[header]));

    // 检查数据有效性
    if (!data.length || !data.every(row => Array.isArray(row) && row.length === headers.length)) {
      errorInfo('导出失败：数据为空');
      return;
    }

    // 直接在数据前插入表头
    data.unshift(headers);

    // 创建工作簿和工作表
    const wb = XLSX.utils.book_new();
    const ws = XLSX.utils.aoa_to_sheet(data);
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

    // 动态生成文件名
    // 获取当前日期并格式化为 YYYY_MM_DD 格式
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以要加1
    const day = String(now.getDate()).padStart(2, '0');

    const formattedDate = `${year}_${month}_${day}`;
    const fileName = `user_export_${formattedDate}.xlsx`;

    // 导出Excel文件
    XLSX.writeFile(wb, fileName);

    // 提示用户导出成功
    OKInfo('导出成功');
  } catch (error) {
    errorInfo('导出失败，请检查控制台日志');
  }
}
</script>

<style scoped>

/* 定义滑动淡入淡出的动画 */
.slide-fade-enter-active {
  transition: all 0.3s ease-out;
}

.slide-fade-leave-active {
  transition: all 0.3s cubic-bezier(1, 0.5, 0.8, 1);
}

.slide-fade-enter-from,
.slide-fade-leave-to {
  transform: translateX(20px);
  opacity: 0;
}
</style>